const http = require("http")
/*
 * 处理环信交互
 * */
exports.init = function() {
	const hx = new huangxin();
	return hx
}

/*
 * 环信服务器处理类
 * */
class huangxin {
	//
	//	grant_type = 'client_credentials';
	//	client_id = 'YXA6xiJPgP6NEeaSVm-VIXAjtw';
	//	client_secret = 'YXA6LkKWbIgzzEM1dVTjzAq7nTCg73k';
	//	appKey = '1113170301115112#com.test.huanxintest1';

	//构造方法
	constructor() {
		this.grant_type = 'client_credentials';
		this.client_id = 'YXA6xiJPgP6NEeaSVm-VIXAjtw';
		this.client_secret = 'YXA6LkKWbIgzzEM1dVTjzAq7nTCg73k';
		this.appKey = '1113170301115112#com.test.huanxintest1';
		this.token = '';
		console.log('实例化huangxin类')
		this.getToken()
	}

	//从服务器更新token
	getToken() {
		console.log('getToken')
		var data = {
			grant_type: 'client_credentials',
			client_id: this.client_id,
			client_secret: this.client_secret
		};
		this._httpPostHX('token', data, (data)=>{
			var d = JSON.parse(data);
			var token = d.access_token;
			console.log(data);
			this.token = token
		})
	}
	
	/*
	 * 注册用户 
	 * */
	signIn(data, callback) {
		console.log('users' + JSON.stringify(data))
		this._httpPostHX('users', data, (data)=>{
			console.log(data);
			const d = JSON.parse(data);
			console.log(d['error'])
			if (d['error']) {
				callback && callback({err: d.error})
			}else {
				callback && callback({err: 0})
			}
			
			
		})
	}
	
	/*
	 * 快速请求
	 * */
	_httpPostHX(path, data, callback) {
		this._http_request({
			data: data,
			path: path,
			method: 'POST',
			callback: function(data) {
				//传进来的函数用来接数据
				if(typeof callback == 'function')
					callback(data);
			}
		});
	}
	
	/*
	 * 发送请求到环信服务器
	 * */
	_http_request(json) {
		var json = json || {};
		json.data = json.data || {};
		json.method = json.method || 'GET';
		json.headers = json.headers || {};
		json.headers['Content-Type'] = 'application/json';
		//json.headers['http']='multipart/form-data';
		json.headers['Authorization'] = 'Bearer ' + this.token;

		var postData = JSON.stringify(json.data); //从json对象中解析出字符串
		//请求参数
		var options = {
			host: 'a1.easemob.com',
			path: '/1113170301115112/com.test.huanxintest1/' + json.path,
			method: json.method,
			headers: json.headers
		};
		//发送请求
		var req = http.request(options, function(res) {
			var chunks = '';
			var size = 0;
			res.setEncoding('utf8'); //设置返回内容的编码
			//存储返回的响应数据
			res.on('data', function(chunk) {
				chunks += chunk;
				size += chunk.length;
			});
			res.on('end', function() {
				//响应完成，获取完整响应数据
				//var data = JSON.parse(Buffer.concat(chunks, size).toString());
				if(typeof json.callback == 'function')
					json.callback(chunks);
			});
		});
		//请求错误时执行的方法
		req.on('error', function(e) {
			console.log('problem with request: ' + e.message);
		});

		// write data to request body
		req.write(postData); //请求体
		req.end(); //请求结束
	}
}